<?php

namespace App\Jobs;

use App\Models\SendGroupSms;
use App\Models\SendGroupSmsLog;
use App\Models\SendVerifyCodeLog;
use App\Traits\Setting;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 发送用户短信
 * Class SendUserSms
 * @package App\Jobs
 */
class SendUserSms extends Job
{
    use Setting;

    /**
     * @var number 被发送电话
     */
    protected $phone;

    /**
     * @var string 发送内容
     */
    protected $content;

    /**
     * @var int 发送记录id
     */
    protected $logId;

    /**
     * @var array 短信配置
     */
    protected $gateways;

    /**
     * Create a new job instance.
     * SendUserSms constructor.
     * @param $phone
     * @param string $content
     * @param int $logId
     * @param array $gateways
     */
    public function __construct($phone, string $content, int $logId, $gateways = [])
    {
        $this->phone = $phone;
        $this->content = $content;
        $this->logId = $logId;
        $this->gateways = $gateways;
    }

    /**
     * Execute the job.
     *
     * @return mixed
     */
    public function handle()
    {
        try {

            // TODO 是否添加模板代码
            $resultTemplateContent = $this->sendSms($this->phone, $this->content, null, $this->gateways);
//            Log::info('发送短信: ',[$resultTemplateContent]);
            $status = data_get($resultTemplateContent, 'status');
            if($status == 'fail'){
                $this->updateGroupSms(SMS_SENDING_FAILED);
                Log::error('发送短信失败，返回错误: ',[$resultTemplateContent]);
                return '发送短信失败';
            }else{
                $this->updateGroupSms(SMS_SENT);
            }

        } catch (\Exception $e) {
            Log::error('发送短信失败 ', (array)$e);
            return false;
        }
    }

    /**
     * 更新发送状态
     * @param $status
     */
    public function updateGroupSms($status){
        DB::beginTransaction();
        try {

            //更新详情表
            $groupSmsLog = SendGroupSmsLog::where('id', $this->logId)->findOrFail($this->logId);

            $groupSmsLog->status = $status;
            $groupSmsLog->updated_at = Carbon::now();

            $groupSmsLog->saveOrFail();

            //更新发送表
            SendGroupSms::where('id', $groupSmsLog->group_sms_id)
                ->update(['updated_at'=>Carbon::now()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('更新发送表失败 '.$e->getMessage());
        }
    }
}
